package yagwl.client.view.fnd;

import java.util.Date;
import java.util.logging.Logger;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Cookies;

public class CookieHandler {

  private static Logger log = Logger.getLogger(CookieHandler.class.getName());
  private String cookieName;
  
  public CookieHandler(String cookieName) {
    this.cookieName = cookieName;
  }

  public String getCookieValue() {
    return Cookies.getCookie(cookieName);
  }

  public void setCookieValue(String cookieValue, boolean persist) {
    Cookies.setCookie(cookieName, cookieValue, getCookieExpiry(persist),
        getCookieDomain(), "/", false);
    log.info("CookieHandler.setCookieValue: " + cookieName + "="
        + cookieValue + "; exp=" + getCookieExpiry(persist) + "; domain="
        + getCookieDomain());
  }

  public void removeCookie() {
    Cookies.removeCookie(cookieName);
    log.info("CookieHandler.removeCookie: " + cookieName);
  }

  private String getCookieDomain() {
    String baseUrl = GWT.getHostPageBaseURL();
    String domain = baseUrl.substring(baseUrl.indexOf("//") + 2, baseUrl
        .indexOf(':', 7));
    return domain;
  }

  private Date getCookieExpiry(boolean persist) {
    if (!persist)
      return null;
    Date now = new Date();
    Date expires = new Date(now.getTime() + 14 * 24 * 60 * 60 * 1000); // 2 weeks
    return expires;
  }

}
